package com.lu.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lu.reggie.common.R;
import com.lu.reggie.entity.User;
import com.lu.reggie.service.IUserService;
import com.lu.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 用户信息 前端控制器
 * </p>
 *
 * @author 况山云
 * @since 2022-08-22
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService iUserService;
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 发送验证码
     * @param user
     * @param session
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session) {
        //获取手机号，验证码
        String phone = user.getPhone();
        if (StringUtils.isNotEmpty(phone)) {
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            //存储到session
            session.setAttribute(phone,code);
            log.info("发送的验证码为:{}", code);
            /*将手机验证码保存到redis，过期时间为5分钟
            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);*/
            return R.success("验证码发送成功!");
        }
        return R.error("验证码发送失败!");
    }

    /**
     * 移动端登陆
     * @param map
     * @param session
     * @return
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession session) {
        //获取前端传递的验证码和手机号
        String phone = map.get("phone").toString();
        Object code = map.get("code");
        System.out.println("=====================");
        log.info("输入的验证码为::{}", code);
       /* //获取redis的验证码
        Object redisCode = redisTemplate.opsForValue().get(phone);*/
        //获取存储在session的验证码
        Object codeSession = session.getAttribute(phone);
        System.out.println("=====================");
        log.info("验证码为::{}", codeSession);
        /*if (codeSession != null && codeSession.equals(code)) {
            //判断有无该账户，没有直接注册
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone, phone);
            User user = iUserService.getOne(queryWrapper);
            if(user == null) {
                //新建user注册
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                iUserService.save(user);
            }
            //将登陆后的用户id保存到session中
            session.setAttribute("user", user.getId());
            return R.success(user);
        }*/
        //判断有无该账户，没有直接注册
        if (phone != null) {
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone, phone);
            User user = iUserService.getOne(queryWrapper);
            if(user == null) {
                //新建user注册
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                iUserService.save(user);
            }
            session.setAttribute("user", user.getId());
            /*删除redis缓存中的验证码
            redisTemplate.delete(phone);*/
            return R.success(user);
        }
        return R.error("登陆失败!");
    }


    @PostMapping("/loginout")
    public R<String> loginOut(HttpServletRequest request) {
        request.getSession().removeAttribute("user");
        return R.success("已退出登录!");
    }
}
